<template>
  <div>
    <input type="file" id="file" ref="file" style="display:none">
    <a-button type="primary"  @click="upload" :loading="loading" >
      <a-icon type="upload" />上传新生数据
    </a-button>
    <!-- <a-button type="link">新生数据导入模板.xsl</a-button> -->
  </div>
</template>

<script>
export default {
  data () {
    return {
      loading: false
    }
  },
  methods: {
    upload () {
      const file = this.$refs.file
      file.value = ''
      file.click() // 选择文件
      const self = this
      file.onchange = function (e) {
        if (!e.target.files.length) {
          return
        }
        const fileData = e.target.files[0]// js 获取文件对象
        const fileName = fileData.name.split('.')[1]
        if (fileName === 'xls' || fileName === 'xlsx') {
          const formData = new FormData()
          formData.append('multipartFile', fileData)
          self.loading = true
          self.$api.upload(formData).then(res => {
            if (res.data.code === 0) {
              self.$message.success(res.data.userMsg)
            } else {
              self.$message.error(res.data.userMsg)
            }
          }).catch(err => {
            console.log(err)
          }).finally(() => {
            self.loading = false
          })
          console.log('发送请求')
        } else {
          self.$message.error('请上传Excel格式的文件')
        }
        console.log(fileData, fileName)
      }
    }
  }
}
</script>
